<template>
  <div class="marketing-management">
    <el-tabs v-model="activeTab" class="marketing-tabs">
      <!-- 优惠券管理 -->
      <el-tab-pane label="优惠券管理" name="coupons">
        <div class="tab-header">
          <el-button type="primary" @click="handleAdd('coupon')">
            <i class="fas fa-plus"></i> 新增优惠券
          </el-button>
        </div>

        <!-- 优惠券列表 -->
        <el-table :data="couponList" border v-loading="loading">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="优惠券名称" min-width="150" />
          <el-table-column prop="type" label="优惠类型" width="100">
            <template #default="scope">
              <el-tag
                :type="scope.row.type === 'discount' ? 'success' : 'warning'"
              >
                {{ scope.row.type === "discount" ? "折扣券" : "满减券" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="优惠内容" width="150">
            <template #default="scope">
              {{
                scope.row.type === "discount"
                  ? `${scope.row.discount}折`
                  : `满${scope.row.minAmount}减${scope.row.amount}`
              }}
            </template>
          </el-table-column>
          <el-table-column prop="validityPeriod" label="有效期" width="200">
            <template #default="scope">
              {{ scope.row.startTime }} 至 {{ scope.row.endTime }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="发放数量" width="100" />
          <el-table-column prop="usedCount" label="已使用" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getCouponStatusType(scope.row.status)">
                {{ getCouponStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button-group>
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit('coupon', scope.row)"
                >
                  <i class="fas fa-edit"></i> 编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete('coupon', scope.row)"
                >
                  <i class="fas fa-trash"></i> 删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
          <template #empty>
            <div class="empty-state">
              <el-empty 
                description="暂无优惠券数据" 
                :image-size="200"
              >
                <div class="empty-text">暂无优惠券数据</div>
                <div class="empty-subtext">添加优惠券后将在此处显示</div>
                <el-button type="primary" @click="handleAdd('coupon')" class="mt-4">添加优惠券</el-button>
              </el-empty>
            </div>
          </template>
        </el-table>
      </el-tab-pane>

      <!-- 促销活动管理 -->
      <el-tab-pane label="促销活动" name="promotions">
        <div class="tab-header">
          <el-button type="primary" @click="handleAdd('promotion')">
            <i class="fas fa-plus"></i> 新增活动
          </el-button>
        </div>

        <!-- 促销活动列表 -->
        <el-table :data="promotionList" border v-loading="loading">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="活动信息" min-width="300">
            <template #default="scope">
              <div class="promotion-info">
                <el-image
                  :src="scope.row.image"
                  :preview-src-list="[scope.row.image]"
                  class="promotion-image"
                />
                <div class="promotion-detail">
                  <div class="title">{{ scope.row.name }}</div>
                  <div class="desc">{{ scope.row.description }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="活动类型" width="100">
            <template #default="scope">
              <el-tag :type="getPromotionTypeTag(scope.row.type)">
                {{ getPromotionTypeLabel(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="活动时间" width="300">
            <template #default="scope">
              {{ scope.row.startTime }} 至 {{ scope.row.endTime }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getPromotionStatusType(scope.row.status)">
                {{ getPromotionStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="scope">
              <el-button-group>
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit('promotion', scope.row)"
                >
                  <i class="fas fa-edit"></i> 编辑
                </el-button>
                <el-button
                  type="success"
                  size="small"
                  @click="handleStats(scope.row)"
                >
                  <i class="fas fa-chart-line"></i> 数据
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete('promotion', scope.row)"
                >
                  <i class="fas fa-trash"></i> 删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
          <template #empty>
            <div class="empty-state">
              <el-empty 
                description="暂无促销活动" 
                :image-size="200"
              >
                <div class="empty-text">暂无促销活动数据</div>
                <div class="empty-subtext">添加促销活动后将在此处显示</div>
                <el-button type="primary" @click="handleAdd('promotion')" class="mt-4">添加促销活动</el-button>
              </el-empty>
            </div>
          </template>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 优惠券编辑对话框 -->
    <el-dialog
      v-model="couponDialogVisible"
      :title="dialogType === 'add' ? '新增优惠券' : '编辑优惠券'"
      width="600px"
    >
      <el-form
        ref="couponFormRef"
        :model="couponForm"
        :rules="couponFormRules"
        label-width="100px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="couponForm.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠类型" prop="type">
          <el-radio-group v-model="couponForm.type">
            <el-radio label="discount">折扣券</el-radio>
            <el-radio label="amount">满减券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="couponForm.type === 'discount' ? '折扣比例' : '优惠金额'"
          prop="value"
        >
          <el-input-number
            v-model="couponForm.value"
            :min="couponForm.type === 'discount' ? 0.1 : 1"
            :max="couponForm.type === 'discount' ? 9.9 : 1000"
            :precision="couponForm.type === 'discount' ? 1 : 0"
            :step="couponForm.type === 'discount' ? 0.1 : 1"
          />
          <span class="unit">{{
            couponForm.type === "discount" ? "折" : "元"
          }}</span>
        </el-form-item>
        <el-form-item
          label="使用门槛"
          prop="minAmount"
          v-if="couponForm.type === 'amount'"
        >
          <el-input-number
            v-model="couponForm.minAmount"
            :min="0"
            :precision="0"
          />
          <span class="unit">元</span>
        </el-form-item>
        <el-form-item label="有效期" prop="validityPeriod">
          <el-date-picker
            v-model="couponForm.validityPeriod"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="发放数量" prop="quantity">
          <el-input-number
            v-model="couponForm.quantity"
            :min="1"
            :precision="0"
          />
        </el-form-item>
        <el-form-item label="使用说明" prop="description">
          <el-input
            type="textarea"
            v-model="couponForm.description"
            :rows="3"
            placeholder="请输入使用说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="couponDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCouponSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 促销活动编辑对话框 -->
    <el-dialog
      v-model="promotionDialogVisible"
      :title="dialogType === 'add' ? '新增促销活动' : '编辑促销活动'"
      width="700px"
    >
      <el-form
        ref="promotionFormRef"
        :model="promotionForm"
        :rules="promotionFormRules"
        label-width="100px"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="promotionForm.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="promotionForm.type" placeholder="请选择活动类型">
            <el-option label="限时折扣" value="flash" />
            <el-option label="满减优惠" value="fullReduction" />
            <el-option label="套餐优惠" value="package" />
            <el-option label="节日特惠" value="festival" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="promotionForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="活动封面" prop="image">
          <el-upload
            class="promotion-upload"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img
              v-if="promotionForm.image"
              :src="promotionForm.image"
              class="upload-image"
            />
            <el-icon v-else class="upload-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input
            type="textarea"
            v-model="promotionForm.description"
            :rows="3"
            placeholder="请输入活动描述"
          />
        </el-form-item>
        <el-form-item label="活动规则" prop="rules">
          <el-input
            type="textarea"
            v-model="promotionForm.rules"
            :rows="3"
            placeholder="请输入活动规则"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="promotionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePromotionSubmit"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

const activeTab = ref("coupons");
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 优惠券列表数据
const couponList = ref([
  {
    id: 1,
    name: "新用户专享券",
    type: "discount",
    discount: 8.5,
    startTime: "2024-03-01",
    endTime: "2024-03-31",
    quantity: 1000,
    usedCount: 100,
    status: "active",
  },
  {
    id: 2,
    name: "满100减20",
    type: "amount",
    minAmount: 100,
    amount: 20,
    startTime: "2024-03-01",
    endTime: "2024-03-31",
    quantity: 500,
    usedCount: 50,
    status: "active",
  },
]);

// 促销活动列表数据
const promotionList = ref([
  {
    id: 1,
    name: "春季特惠",
    description: "春季旅游特惠活动",
    image: "https://example.com/promotion1.jpg",
    type: "flash",
    startTime: "2024-03-01 00:00:00",
    endTime: "2024-03-31 23:59:59",
    status: "active",
  },
]);

// 对话框相关
const dialogType = ref("add");
const couponDialogVisible = ref(false);
const promotionDialogVisible = ref(false);
const couponFormRef = ref(null);
const promotionFormRef = ref(null);

// 优惠券表单
const couponForm = reactive({
  name: "",
  type: "discount",
  value: 0,
  minAmount: 0,
  validityPeriod: [],
  quantity: 1,
  description: "",
});

// 促销活动表单
const promotionForm = reactive({
  name: "",
  type: "",
  timeRange: [],
  image: "",
  description: "",
  rules: "",
});

// 表单验证规则
const couponFormRules = {
  name: [{ required: true, message: "请输入优惠券名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择优惠类型", trigger: "change" }],
  value: [{ required: true, message: "请输入优惠值", trigger: "blur" }],
  validityPeriod: [
    { required: true, message: "请选择有效期", trigger: "change" },
  ],
  quantity: [{ required: true, message: "请输入发放数量", trigger: "blur" }],
};

const promotionFormRules = {
  name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择活动类型", trigger: "change" }],
  timeRange: [{ required: true, message: "请选择活动时间", trigger: "change" }],
  image: [{ required: true, message: "请上传活动封面", trigger: "change" }],
  description: [{ required: true, message: "请输入活动描述", trigger: "blur" }],
};

// 优惠券状态
const getCouponStatusType = (status) => {
  const statusMap = {
    active: "success",
    expired: "info",
    disabled: "danger",
  };
  return statusMap[status] || "info";
};

const getCouponStatusLabel = (status) => {
  const statusMap = {
    active: "生效中",
    expired: "已过期",
    disabled: "已停用",
  };
  return statusMap[status] || "未知";
};

// 促销活动类型
const getPromotionTypeTag = (type) => {
  const typeMap = {
    flash: "danger",
    fullReduction: "warning",
    package: "success",
    festival: "primary",
  };
  return typeMap[type] || "info";
};

const getPromotionTypeLabel = (type) => {
  const typeMap = {
    flash: "限时折扣",
    fullReduction: "满减优惠",
    package: "套餐优惠",
    festival: "节日特惠",
  };
  return typeMap[type] || "未知";
};

// 促销活动状态
const getPromotionStatusType = (status) => {
  const statusMap = {
    upcoming: "warning",
    active: "success",
    ended: "info",
  };
  return statusMap[status] || "info";
};

const getPromotionStatusLabel = (status) => {
  const statusMap = {
    upcoming: "未开始",
    active: "进行中",
    ended: "已结束",
  };
  return statusMap[status] || "未知";
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  loadData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadData();
};

// 加载数据
const loadData = () => {
  loading.value = true;
  // TODO: 根据activeTab调用相应的API
  setTimeout(() => {
    loading.value = false;
  }, 1000);
};

// 新增
const handleAdd = (type) => {
  dialogType.value = "add";
  if (type === "coupon") {
    Object.keys(couponForm).forEach((key) => {
      couponForm[key] = "";
    });
    couponForm.type = "discount";
    couponForm.value = 0;
    couponForm.quantity = 1;
    couponDialogVisible.value = true;
  } else {
    Object.keys(promotionForm).forEach((key) => {
      promotionForm[key] = "";
    });
    promotionForm.timeRange = [];
    promotionDialogVisible.value = true;
  }
};

// 编辑
const handleEdit = (type, row) => {
  dialogType.value = "edit";
  if (type === "coupon") {
    Object.keys(couponForm).forEach((key) => {
      couponForm[key] = row[key];
    });
    couponDialogVisible.value = true;
  } else {
    Object.keys(promotionForm).forEach((key) => {
      promotionForm[key] = row[key];
    });
    promotionForm.timeRange = [row.startTime, row.endTime];
    promotionDialogVisible.value = true;
  }
};

// 删除
const handleDelete = (type, row) => {
  ElMessageBox.confirm("确定要删除该记录吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // TODO: 调用删除API
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};

// 查看数据统计
const handleStats = (row) => {
  // TODO: 实现数据统计查看逻辑
  console.log("查看数据统计", row);
};

// 图片上传
const handleUploadSuccess = (response) => {
  promotionForm.image = response.url;
  ElMessage.success("上传成功");
};

const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("上传文件只能是图片格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 提交表单
const handleCouponSubmit = async () => {
  if (!couponFormRef.value) return;

  await couponFormRef.value.validate((valid, fields) => {
    if (valid) {
      // TODO: 调用保存API
      ElMessage.success(dialogType.value === "add" ? "添加成功" : "更新成功");
      couponDialogVisible.value = false;
      loadData();
    }
  });
};

const handlePromotionSubmit = async () => {
  if (!promotionFormRef.value) return;

  await promotionFormRef.value.validate((valid, fields) => {
    if (valid) {
      // TODO: 调用保存API
      ElMessage.success(dialogType.value === "add" ? "添加成功" : "更新成功");
      promotionDialogVisible.value = false;
      loadData();
    }
  });
};
</script>

<style scoped>
.marketing-management {
  padding: 20px;
}

.marketing-tabs {
  margin-bottom: 20px;
}

.tab-header {
  margin-bottom: 20px;
}

.promotion-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.promotion-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.promotion-detail {
  flex: 1;
}

.promotion-detail .title {
  font-weight: bold;
  margin-bottom: 5px;
}

.promotion-detail .desc {
  color: #666;
  font-size: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.unit {
  margin-left: 10px;
  color: #666;
}

.promotion-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.promotion-upload .el-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.upload-image {
  width: 178px;
  height: 178px;
  display: block;
}

/* 空状态样式 */
.empty-state {
  padding: 40px 0;
  text-align: center;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
